import React, { Component } from "react";
import "./Tabbar.scss";

export default class Tabbar extends Component {
  state = {
    activeTab: "home",
    activeTabPathMap: {
      home: "/home",
      category: "/category",
      cart: "/cart",
      my: "/my",
    },
  };

  componentDidMount() {
    // console.log(this.props);
    let activeTab = this.props.match.url.split("/")[1];
    this.setState({
      activeTab,
    });
    // 监听hash的变化
    window.addEventListener("hashchange", this.handleHashChange);
  }

  handleHashChange = () => {
    let activeTab = this.props.match.url.split("/")[1];
    this.setState({
      activeTab,
    });
  };

  handleClick = (activeTab) => {
    this.setState({
      activeTab,
    });
    // 跳转路由
    this.props.history.push(this.state.activeTabPathMap[activeTab]);
  };

  componentWillUnmount(){
    window.removeEventListener("hashchange",this.handleHashChange);
  }
  
  render() {
    return (
      <div className="tabbarContainer">
        {/* tabbar内容栏 */}
        <div className="tabbarContent">{this.props.children}</div>

        {/* 底部导航栏 */}
        <div className="tabbar">
          {/* 首页 */}
          <div className="tabbarItem" onClick={this.handleClick.bind(this, "home")}>
            <i
              className={this.state.activeTab === "home" ? "icon icon-home-o" : "icon icon-home"}
            ></i>

            <span className={this.state.activeTab === "home" ? "title active" : "title"}>首页</span>
          </div>

          {/* 分类 */}
          <div className="tabbarItem" onClick={this.handleClick.bind(this, "category")}>
            <i
              className={
                this.state.activeTab === "category"
                  ? "icon icon-community-o"
                  : "icon icon-community"
              }
            ></i>

            <span className={this.state.activeTab === "category" ? "title active" : "title"}>
              分类
            </span>
          </div>

          {/* 购物车 */}
          <div className="tabbarItem" onClick={this.handleClick.bind(this, "cart")}>
            <i
              className={this.state.activeTab === "cart" ? "icon icon-cart-o" : "icon icon-cart"}
            ></i>

            <span className={this.state.activeTab === "cart" ? "title active" : "title"}>
              购物车
            </span>
          </div>

          {/* 我的 */}
          <div className="tabbarItem" onClick={this.handleClick.bind(this, "my")}>
            <i className={this.state.activeTab === "my" ? "icon icon-my-o" : "icon icon-my"}></i>

            <span className={this.state.activeTab === "my" ? "title active" : "title"}>我的</span>
          </div>
        </div>
      </div>
    );
  }
}
